package com.icee.myth.common.channelBuffer;

/**
 * 在netty4中线程模型中，不需要用户自己处理发包线程，所以这个类也就不需要了。
 * @author liuxianke

public class NewChannelBuffers {
    public static ByteBuf wrappedBuffer(ArrayList<Object> buffers) {
        int size = buffers.size();
        switch (size) {
            case 0:
                break;
            case 1: {
                ByteBuf cb = (ByteBuf)buffers.get(0);
                if (cb.isReadable()) {
                    return Unpooled.wrappedBuffer(cb); //ChannelBuffers.wrappedBuffer(cb);
                }
                break;
            }
            default: {
                ByteOrder order = null;
                final ArrayList<ByteBuf> components = new ArrayList<ByteBuf>(size);
                for (int i=0; i<size; i++) {
                    ByteBuf cb = (ByteBuf)buffers.get(i);
                    if (cb == null) {
                        break;
                    }
                    if (cb.isReadable()) {
                        if (order != null) {
                            if (!order.equals(cb.order())) {
                                throw new IllegalArgumentException(
                                        "inconsistent byte order");
                            }
                        } else {
                            order = cb.order();
                        }
                        if (cb instanceof CompositeByteBuf) {
                            // Expand nested composition.
                            components.addAll(
                                    ((CompositeByteBuf) cb).decompose(
                                            cb.readerIndex(), cb.readableBytes()));
                        } else {
                            // An ordinary buffer (non-composite)
                            components.add(cb.slice());
                        }
                    }
                }
                return compositeBuffer(order, components);
            }
        }
        return EMPTY_BUFFER;
    }

    private static ByteBuf compositeBuffer(ByteOrder endianness, List<ByteBuf> components) {
        switch (components.size()) {
            case 0:
                return EMPTY_BUFFER;
            case 1:
                return components.get(0);
            default:
                //创建复合缓冲区
                CompositeByteBuf compBuf = Unpooled.compositeBuffer();
                compBuf.addComponents(components);
                compBuf.order(endianness);
                return compBuf;
        }
    }

    public static ByteBuf buildVarint32(int data) {
        byte[] bytes = new byte[CodedOutputStream.computeRawVarint32Size(data)];
        int index = 0;
        while (true) {
          if ((data & ~0x7F) == 0) {
              bytes[index++] = (byte)data;
              break;
          } else {
              bytes[index++] = (byte)((data & 0x7F) | 0x80);
              data >>>= 7;
          }
        }

        return Unpooled.wrappedBuffer(bytes);
    }
}
 */